﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Management;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using System.Net;
using System.Web.Services;
using System.Web.Services.Protocols;

namespace AzureDriveExplorer
{
    public partial class FormMain : Form
    {

        //Azure
        private static GetListVHD.AzureDriveExplorerServiceSoapClient list = new GetListVHD.AzureDriveExplorerServiceSoapClient();
        //Local Azure
        //private static GetListVHDLocalAzure.WebService1SoapClient list = new GetListVHDLocalAzure.WebService1SoapClient();
        //Local
        //private static GetListVHDLocal.Service1SoapClient list = new GetListVHDLocal.Service1SoapClient();
        private bool ReadWrite = false;
        private static long MaxBit = 655360;
        private int numLanguage = 0;

        Log log = new Log();
        Constant constant = new Constant();

        public FormMain()
        {

            InitializeComponent();
            initializeListFile();
        }
        protected void initializeListFile()
        {
            language(numLanguage);

            ////Directory
            treeView1.ImageList = this.imageListTree;

            System.Management.ManagementObjectSearcher ms = new System.Management.ManagementObjectSearcher("SELECT * FROM win32_logicaldisk");
            foreach (ManagementObject mo in ms.Get())
            {

                string path = mo["deviceid"].ToString() + "\\";
                try
                {

                    string[] filePaths = Directory.GetDirectories(path);


                    treeView1.Nodes.Add(path, path, 0, 0);
                    if (filePaths.Length > 0)
                    {

                        foreach (string dir in filePaths)
                        {

                            treeView1.Nodes[path].Nodes.Add(dir, LastNamePath(dir), 1, 2);
                        }
                    }

                }
                catch { }

            }

            this.Load += new EventHandler(fMain_Load);

            //Azure Get List
            //ListContainers();
            //local
            //GetListAzure();

        }

        void fMain_Load(object sender, EventArgs e)
        {
            showSplashScreen(1);
        }
        private void showSplashScreen(int refresh)
        {
            //Azure
            GetListVHD.ArrayOfString ListVHD = null;
           

            //initialize
            if (refresh == 1)
            {
                using (Loading fsplash = new Loading())
                {
                    if (fsplash.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) this.Close();
                    ListVHD = fsplash.ListVHD;
                }
            }
            //refresh
            else
            {
                using (Reload fsplash = new Reload())
                {
                    if (fsplash.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) this.Close();
                    ListVHD = fsplash.ListVHD;
                }
            }


            treeView1.Nodes.Add(Constant.Azure + @"\", Constant.Azure, 5, 5);

            if (ListVHD != null)
                foreach (string str in ListVHD)
                    treeView1.Nodes[Constant.Azure + @"\"].Nodes.Add(FirstNamePath(str) + "\\", str, 0, 0);

            // foreach (string str in listDirectory)
            //    treeView1.Nodes[@"Azure\"].Nodes[FirstNamePath(listDirectory[0]) + "\\"].Nodes.Add(@"Azure\" + str, LastNamePath(str), 2, 1);

        }


        private void GetListAzure()
        {

            //GetListVHD.Service1SoapClient list = new GetListVHD.Service1SoapClient();
            //Azure
            GetListVHD.ArrayOfString ListVHD;
            //Local Azure
            //GetListVHDLocalAzure.ArrayOfString ListVHD;

            //Local
            //GetListVHDLocal.ArrayOfString listDirectory, listFiles, ListVHD;

            GetListVHD.ArrayOfString vecFileAccount = new GetListVHD.ArrayOfString();
            
            List<string> ListFileAccount = new List<string>();
            //read file account
            try
            {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader(Constant.FileConfig))
                {
                    String line;
                    // Read and display lines from the file until the end of 
                    // the file is reached.
                    while ((line = sr.ReadLine()) != null)
                    {
                        vecFileAccount.Add(line);
                    }
                }
            }
            catch (Exception ex)
            {
                // Let the user know what went wrong.
                MessageBox.Show(constant.idioma(0, 1), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //log.Logs("Error", ex.Message);
            }

            //listDirectory = list.getDirectory();
            //listFiles = list.getFiles();
            ListVHD = list.getVHD(vecFileAccount, Constant.key());

            treeView1.Nodes.Add(Constant.Azure + @"\", Constant.Azure, 5, 5);

            foreach (string str in ListVHD)
                treeView1.Nodes[Constant.Azure + @"\"].Nodes.Add(FirstNamePath(str) + "\\", str, 0, 0);

            // foreach (string str in listDirectory)
            //    treeView1.Nodes[@"Azure\"].Nodes[FirstNamePath(listDirectory[0]) + "\\"].Nodes.Add(@"Azure\" + str, LastNamePath(str), 2, 1);

        }

        private List<string> getListDirectoryAzure(string path)
        {
            //GetListVHD.Service1SoapClient list = new GetListVHD.Service1SoapClient();
            //Azure
            GetListVHD.ArrayOfString listDirectory;
            //Local Azure
            //GetListVHDLocalAzure.ArrayOfString listDirectory;
            //Local
            //GetListVHDLocal.ArrayOfString listDirectory;

            List<string> strlist = new List<string>();
            listDirectory = list.getDirectory(WithNotFirstPath(path), Constant.key());

            foreach (string str in listDirectory)
                strlist.Add(str);
            //    treeView1.Nodes[@"Azure\"].Nodes.Add(path, LastNamePath(str), 2, 1);

            return strlist;

        }

        private List<string> getLlistFilesAzure(string path)
        {
            //GetListVHD.Service1SoapClient list = new GetListVHD.Service1SoapClient();
            //Azure
            GetListVHD.ArrayOfString listFiles;
            //Local Azure
            //GetListVHDLocalAzure.ArrayOfString listFiles;
            //local
            //GetListVHDLocal.ArrayOfString listFiles;


            List<string> strlist = new List<string>();
            listFiles = list.getFiles(WithNotFirstPath(path), Constant.key());

            foreach (string str in listFiles)
                strlist.Add(str);

            return strlist;
        }


        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {

            string str_dir = string.Empty;

            if (!e.Node.FullPath.Equals(""))
            {
                try
                {
                    if (FirstNamePath(e.Node.FullPath).Equals(Constant.Azure))
                    {


                        listView1.Clear();

                        // FillImageList(filePaths);
                        foreach (string dir in getLlistFilesAzure(e.Node.FullPath))
                        {

                            listView1.Items.Add(dir, LastNamePath(dir), fileIcoSearch(LastNamePath(dir)));

                        }


                    }
                    else
                    {


                        ////Directory
                        //try
                        //{

                        //    string[] filePaths = Directory.GetDirectories(e.Node.FullPath);
                        //    if (filePaths.Length > 0)
                        //    {
                        //        if (e.Node.Nodes.Count == 0)
                        //            foreach (string dir in filePaths)
                        //            {
                        //                //str_dir = dir;//.Replace("\\", "/");
                        //                e.Node.Nodes.Add(str_dir, LastNamePath(dir), 1, 2);
                        //            }
                        //    }

                        //}
                        //catch { }


                        ////File


                        listView1.Clear();

                        string[] filePaths = Directory.GetFiles(e.Node.FullPath);
                        if (filePaths.Length > 0)
                        {
                            // FillImageList(filePaths);
                            foreach (string dir in filePaths)
                            {
                                //str_dir = dir.Replace("\\", "/");

                                //foreach (string path in filePaths)
                                //{
                                listView1.Items.Add(dir, LastNamePath(dir), fileIcoSearch(LastNamePath(dir)));
                                //listView1.Items[1].Tag = dir;
                                //}


                                //e.Node.Nodes.Add("", PathName(str_dir), 4, 4);
                            }
                        }


                    }
                }
                catch { }
            }
            //else
            //   viewImage(e.Node.FullPath);

        }

        /// <summary>
        /// treeviweを開いているとき
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
        {
            for (int i = 0; i < e.Node.Nodes.Count; i++)
            {
                string str_dir = string.Empty;
                //Azure
                if (!e.Node.Nodes[i].FullPath.Equals(""))
                {

                    try
                    {
                        //if (e.Node.Nodes.Count == 0)
                        if (FirstNamePath(e.Node.Nodes[i].FullPath).Equals(Constant.Azure))
                        {

                            if (e.Node.Nodes[i].Nodes.Count == 0)
                                foreach (string dir in getListDirectoryAzure(e.Node.Nodes[i].FullPath))
                                {
                                    e.Node.Nodes[i].Nodes.Add(str_dir, LastNamePath(dir), 1, 2);
                                }

                        }
                        else
                        {

                            ////Directory


                            string[] filePaths = Directory.GetDirectories(e.Node.Nodes[i].FullPath);
                            if (filePaths.Length > 0)
                            {
                                if (e.Node.Nodes[i].Nodes.Count == 0)
                                    foreach (string dir in filePaths)
                                    {
                                        e.Node.Nodes[i].Nodes.Add(str_dir, LastNamePath(dir), 1, 2);
                                    }
                            }

                        }

                    }
                    catch { }


                }

            }


        }

        #region DragDrop
        private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
        {

            DoDragDrop(e.Item, DragDropEffects.Move);
        }

        private void listView1_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }




        private void treeView1_DragEnter(object sender, DragEventArgs e)
        {

            e.Effect = DragDropEffects.Move;

        }

        private void treeView1_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(ListViewItem)))
            {
                //initialize 
                progressBar1.Visible = true;
                ListViewItem li = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
                TreeNode DestinationNode = ((TreeView)sender).GetNodeAt(pt);

                //upload
                if (FirstNamePath(DestinationNode.FullPath).Equals(Constant.Azure))
                {

                    if (!DestinationNode.FullPath.Contains("\\"))
                        return;


                    ListView.SelectedListViewItemCollection breakfast = this.listView1.SelectedItems;
                    int countFileSend = 1;
                    foreach (ListViewItem item in breakfast)
                    {
                        label1.Text = countFileSend.ToString() + " / " + breakfast.Count.ToString() + " [" + item.Text + "] ";
                        if (!FirstNamePath(treeView1.SelectedNode.FullPath).Equals(Constant.Azure))
                        {
                            uploadFile(WithNotFirstPath(DestinationNode.FullPath), item.Name);
                        }
                        else
                        {
                            MessageBox.Show(constant.idioma(numLanguage, 156), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        countFileSend++;
                    }

                }
                //Download
                else
                {
                    ListView.SelectedListViewItemCollection breakfast = this.listView1.SelectedItems;
                    int countFileSend = 1;
                    foreach (ListViewItem item in breakfast)
                    {
                        label1.Text = countFileSend.ToString() + " / " + breakfast.Count.ToString() + " [" + item.Text + "] ";
                        if (FirstNamePath(treeView1.SelectedNode.FullPath).Equals(Constant.Azure))
                        {
                            DownloadFile(DestinationNode.FullPath, item.Name);
                        }
                        else
                            MessageBox.Show(constant.idioma(numLanguage, 156), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //SaveFile(DestinationNode.FullPath, LastNamePath(item.Name), DownloadFile(item.Name));
                        countFileSend++;
                    }
                }

                //clear and visible = false
                progressBar1.Visible = false;
                label1.Text = string.Empty;

            }
        }

        private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            DoDragDrop(e.Item, DragDropEffects.Move);
        }
        #endregion

        #region download
        protected void SaveFile(string path, string name, byte[] file)
        {
            try
            {
                File.WriteAllBytes(path + name, file);

            }
            catch
            { }

        }


        protected void DownloadFile(string outPath, string InPath)
        {
            try
            {
                string info = string.Empty;

                backgroundWorker1.ReportProgress(0);
                SecondDownload(InPath, outPath);
                return;
            }
            catch
            {
                SecondDownload(InPath, outPath);
                cancel(outPath); list.Cancel(InPath);
            }
            finally
            {
                list.Cancel(InPath); cancel(outPath);
            }

            progressBar1.Value = 0;
        }


        protected void SecondDownload(string InPath, string outPath)
        {
            progressBar1.Visible = true;
            progressBar1.Step = 1;
            ProgressMessenger(constant.idioma(numLanguage, 121));
            progressBar1.Value = 10;
            //backgroundWorker1.ReportProgress(1);
            string path = string.Empty;
            try
            {
                progressBar1.Value = 10;
                //backgroundWorker1.ReportProgress(1);
                path = list.getCopyToDownload(InPath);
            }
            catch
            {
                progressBar1.Value = 20;
                //backgroundWorker1.ReportProgress(2);
                if (path.Equals(""))
                {
                    ProgressMessenger(constant.idioma(numLanguage, 122));
                    System.Threading.Thread.Sleep(1000);                    
                    path = list.getCopyURLDownload(InPath);
                }
            }

            if (!path.Substring(0, 4).ToUpper().Equals("HTTP"))
            {
                ProgressMessenger(constant.idioma(numLanguage, 122));
                System.Threading.Thread.Sleep(1000);
                path = list.getCopyURLDownload(InPath);
            }

            if (!path.Equals(null))
            {
                //path = list.getCopyURLDownload(InPath);
                progressBar1.Value = 30;// backgroundWorker1.ReportProgress(3);
                WebClient webClient = new WebClient();
                progressBar1.Value = 40;//backgroundWorker1.ReportProgress(4);
                webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
                progressBar1.Value = 50; //backgroundWorker1.ReportProgress(5);
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
                progressBar1.Value = 60; //backgroundWorker1.ReportProgress(6);
                webClient.DownloadFileAsync(new Uri(path), outPath + "\\" + LastNamePath(InPath));
                progressBar1.Value = 90; //backgroundWorker1.ReportProgress(9);
                ProgressMessenger(constant.idioma(numLanguage, 123));
            }
            else
            {
                MessageBox.Show(constant.idioma(numLanguage, 124), "", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

            bool a=list.getDeleteFileWeb(InPath);
            progressBar1.Value = 100; //backgroundWorker1.ReportProgress(10);
            System.Threading.Thread.Sleep(3000);

        }



        protected void ProgressMessenger(string messenger)
        {
            label1.Text = messenger;
            label1.Refresh();
        }

        protected void CreateFinishPaketDownload(long file, string InPath, string OutPath, long pakets)
        {
            byte[] outfile = new byte[file];
            long byteCount = 0;
            long byteCountCopy = 0;
            long count = 0;
            try
            {
                while (count < pakets)
                {
                    byte[] TempFile = ReadFile(InPath + Constant.Pont + count);
                    while (byteCountCopy < TempFile.Length)
                    {
                        outfile[byteCount] = TempFile[byteCountCopy];
                        byteCount++;
                        byteCountCopy++;
                    }
                    byteCountCopy = 0;
                    count++;
                }

                File.WriteAllBytes(OutPath, outfile);
            }
            catch { }
            finally
            {
                count = 0;
                while (count < pakets)
                {
                    File.Delete(InPath + Constant.Pont + count);
                    count++;
                }
            }



        }
        #endregion

        #region test
        public byte[] getFile(string path)
        {


            byte[] buffer = null;
            try
            {
                buffer = File.ReadAllBytes(path);
            }
            catch (Exception ex)
            {

            }

            return buffer;

        }

        protected string getFilePaket(string path)
        {
            byte[] file = File.ReadAllBytes(path);
            //65536 bit is recomende for sending, in case send more bits, meaby lost the paket
            long numPakets = 0;
            byte[] sendPaket = new byte[MaxBit];
            byte[] addnewfile;
            byte[] newfiles = new byte[file.Length];
            //File.WriteAllBytes("d:\\1.rar", newfiles);

            decimal loop = 0, count = 0;

            path = FirstNamePath(path);
            DateTime datetime = DateTime.Now;
            string outName = datetime.ToString("yyyyMMddHHmmss");

            loop = decimal.Divide(file.Length, MaxBit);
            try
            {
                while (count < getWithOutDecimal(loop))
                {
                    addnewfile = getPaket(file, long.Parse((count * MaxBit).ToString()), MaxBit);
                    newfile(path + "\\" + outName, addnewfile, long.Parse((count * MaxBit).ToString()), MaxBit);
                    count++;
                    numPakets++;

                }

                if (loop > count)
                {
                    long loopDecimal = long.Parse(count.ToString()) * MaxBit;
                    long countDecimal = 0;

                    //while (countDecimal < loopDecimal)
                    //{
                    addnewfile = getLastPaket(file, (long)loopDecimal, MaxBit);
                    newfile(path + "\\" + outName, addnewfile, (long)loopDecimal, MaxBit);
                    countDecimal++;
                    //}
                    numPakets++;
                }



            }
            catch { cancel(path + "\\" + outName); }


            return path + "\\" + outName + "-" + numPakets.ToString() + "-" + file.Length;

        }
        #endregion

        #region upload
        protected void uploadFile(string Inpath, string Outname)
        {
            //ListView.SelectedListViewItemCollection breakfast = this.listView1.SelectedItems;

            //foreach (ListViewItem item in breakfast)
            //{

            //if (list.CreateFile(file.Length.ToString(), Inpath, LastNamePath(Outname)))
            //    MessageBox.Show("エラー、ファイルをアップロードができませんでした" + Outname);
            //else


            byte[] file = ReadFile(Outname);

            SendSocket(Inpath, Outname, file);

            //}
        }

        protected void SendSocket(string InPath, string OutPath, byte[] file)
        {
            //65536 bit is recomende for sending, in case send more bits, meaby lost the paket
            long fileLength = file.Length;
            long numPakets = 0;
            byte[] sendPaket = new byte[MaxBit];
            byte[] addnewfile;
            //byte[] newfiles = new byte[fileLength];
            //File.WriteAllBytes("d:\\1.rar", newfiles);

            decimal loop = 0, count = 0;

            loop = decimal.Divide(fileLength, MaxBit);

            progressBar1.Step = (int)loop + 1;

            try
            {
                while (count < getWithOutDecimal(loop))
                {
                    addnewfile = getPaket(file, long.Parse((count * MaxBit).ToString()), MaxBit);
                    list.newfile(InPath + LastNamePath(OutPath), addnewfile, long.Parse((count * MaxBit).ToString()), MaxBit);
                    count++;
                    numPakets++;


                    backgroundWorker1.ReportProgress((int)count * 100 / ((int)loop + 1));


                    System.Threading.Thread.Sleep(100);

                }

                if (loop > count)
                {
                    long loopDecimal = long.Parse(count.ToString()) * MaxBit;
                    long countDecimal = 0;

                    //while (countDecimal < loopDecimal)
                    //{
                    addnewfile = getLastPaket(file, (long)loopDecimal, MaxBit);
                    list.newfile(InPath + LastNamePath(OutPath), addnewfile, (long)loopDecimal, MaxBit);
                    countDecimal++;
                    //}
                    numPakets++;
                }
                progressBar1.Step = progressBar1.Step;

                if (list.CreateFinishPaket(fileLength, InPath + LastNamePath(OutPath), numPakets))
                    cancel(InPath + LastNamePath(OutPath));
            }
            catch { cancel(InPath + LastNamePath(OutPath)); }
            finally { file = null; }
            progressBar1.Value = 0;

        }

        protected void newfile(string OutPath, byte[] paket, long beginner, long maxNumberbits)
        {
            decimal loop = decimal.Divide(beginner, maxNumberbits);

            File.WriteAllBytes(OutPath + "." + loop.ToString(), paket);
        }





        protected void CreateFinishPaket(long file, string OutPath, long pakets)
        {
            byte[] outfile = new byte[file];
            long byteCount = 0;
            long byteCountCopy = 0;
            long count = 0;
            while (count < pakets)
            {
                byte[] TempFile = ReadFile(OutPath + "." + count);
                while (byteCountCopy < TempFile.Length)
                {
                    outfile[byteCount] = TempFile[byteCountCopy];
                    byteCount++;
                    byteCountCopy++;
                }
                byteCountCopy = 0;
                count++;
            }
            count = 0;
            while (count < pakets)
            {
                File.Delete(OutPath + "." + count);
                count++;
            }
            File.WriteAllBytes(OutPath, outfile);
        }


        protected byte[] getPaket(byte[] file, long beginner, long maxNumberbits)
        {
            byte[] paket = new byte[maxNumberbits];
            long count = 0;
            while (count < maxNumberbits)
            {
                paket[count] = file[beginner + count];

                count++;
            }
            return paket;

        }

        protected byte[] getLastPaket(byte[] file, long beginner, long maxNumberbits)
        {
            byte[] paket = new byte[file.Length - beginner];
            long count = beginner, paketCount = 0;
            while (count < file.Length)
            {
                paket[paketCount] = file[count];
                paketCount++;
                count++;
            }
            return paket;

        }

        public static byte[] ReadFile(string filePath)
        {
            byte[] buffer = null;
            try
            {
                buffer = File.ReadAllBytes(filePath);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            return buffer;
        }
        # endregion

        private decimal getDecimal(decimal number)
        {
            decimal result = 0;
            try
            {
                string[] strNumber = number.ToString().Split(Constant.PontChar);
                if (strNumber.Length == 2)
                    result = decimal.Parse(strNumber[1]);

            }
            catch { }
            return result;
        }

        private decimal getWithOutDecimal(decimal number)
        {
            decimal result = 0;
            try
            {
                string[] strNumber = number.ToString().Split(Constant.PontChar);
                result = decimal.Parse(strNumber[0]);

            }
            catch { }
            return result;
        }

        #region text split
        private string WithNotFirstPath(string oldName)
        {
            string str_Name = string.Empty;
            string[] str_Split = oldName.Split('\\');
            for (int i = 1; i < str_Split.Length; i++)
                if (!str_Split[i].Equals(""))
                    str_Name += str_Split[i] + '\\';

            return str_Name;
        }

        private string LastNamePath(string oldName)
        {
            string str_Name = string.Empty;
            string[] str_Split = oldName.Split('\\');
            for (int i = 0; i < str_Split.Length; i++)
                if (!str_Split[i].Equals(""))
                    str_Name = str_Split[i];

            return str_Name;

        }

        private string FirstNamePath(string oldName)
        {
            string str_Name = string.Empty;
            string[] str_Split = oldName.Split('\\');
            for (int i = str_Split.Length - 1; i > -1; i--)
                if (!str_Split[i].Equals(""))
                    str_Name = str_Split[i];

            return str_Name;

        }
        #endregion

        private int fileIcoSearch(string Extension)
        {
            int fileindex = 0;
            try
            {
                string[] ext = Extension.Split(Constant.PontChar);


                switch (ext[ext.Length - 1].ToLower())
                {
                    case "doc": fileindex = 1; break;
                    case "docx": fileindex = 1; break;
                    case "xls": fileindex = 2; break;
                    case "xlsx": fileindex = 2; break;
                    case "txt": fileindex = 3; break;
                    case "jpg": fileindex = 4; break;
                    case "jpeg": fileindex = 4; break;
                    case "dll": fileindex = 5; break;
                    case "html": fileindex = 6; break;
                    case "htm": fileindex = 6; break;
                    case "zip": fileindex = 7; break;
                    case "rar": fileindex = 7; break;
                    case "bmp": fileindex = 8; break;

                }
            }
            catch { }

            return fileindex;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (DialogResult.No == MessageBox.Show(constant.idioma(numLanguage, 160), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            { return; }
            
            ListView.SelectedListViewItemCollection breakfast = this.listView1.SelectedItems;
            foreach (ListViewItem item in breakfast)
            {
                if (list.DeleteFile(item.Name, Constant.key()))
                    MessageBox.Show(constant.idioma(numLanguage, 136) + item.Name + constant.idioma(numLanguage, 137));
                else
                    this.listView1.Items.RemoveAt(item.Index);
            }
        }

        #region progressBar
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int result = (int)e.Argument;

            backgroundWorker1.ReportProgress(result);
            e.Result = (int)e.Argument;
        }

        private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            this.progressBar1.Visible = true;
            ProgressMessenger(constant.idioma(numLanguage, 123) + e.ProgressPercentage.ToString() + Constant.Percent);
            progressBar1.Value = e.ProgressPercentage;
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {


            this.progressBar1.Value = e.ProgressPercentage;
            ProgressMessenger(constant.idioma(numLanguage, 123) + e.ProgressPercentage.ToString() + Constant.Percent);
            //progressBar1.PerformStep();
            this.label1.Text = this.label1.Text;
            label1.Refresh();

        }

        private void Completed(object sender, AsyncCompletedEventArgs e)
        {
            progressBar1.Visible = false;
            ProgressMessenger(constant.idioma(numLanguage, 125));
            ProgressMessenger("");

        }
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBar1.Visible = false;
            ProgressMessenger(constant.idioma(numLanguage, 125));
            ProgressMessenger("");

        }

        private void progressBar1_ParentChanged(object sender, EventArgs e)
        {

        }
        #endregion

        protected void cancel(string outpath)
        {
            list.Cancel(outpath);
        }

        protected bool initializeFolder(string path)
        {

            try
            {
                if (!Directory.Exists(path))
                {
                    // Create Directory temp
                    Directory.CreateDirectory(path);
                    // Create Directory Download
                    Directory.CreateDirectory(path);
                    // Create Directory Upload
                    Directory.CreateDirectory(path);

                    ReadWrite = true;
                }
                else
                {
                    MessageBox.Show(path + constant.idioma(numLanguage, 126), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch
            {
                ReadWrite = true;
            }
            return ReadWrite;
        }

        private void button2_Click(object sender, EventArgs e)
        {

            if (!FirstNamePath(treeView1.SelectedNode.FullPath).Equals(Constant.Azure))
            {
                MessageBox.Show(constant.idioma(numLanguage, 127), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;

            }
            if (treeView1.SelectedNode.FullPath.Equals(Constant.Azure))
            {
                MessageBox.Show(constant.idioma(numLanguage, 128), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }


            CreateFolder testDialog = new CreateFolder(numLanguage);

            // Show testDialog as a modal dialog and determine if DialogResult = OK.

            if (testDialog.ShowDialog(this) == DialogResult.OK)
            {
                // Read the contents of testDialog's TextBox.
                //MessageBox.Show(testDialog.textBox1.Text);

                bool returnText = false;
                if (testDialog.textBox1.Text.Equals(""))
                    returnText = true;
                if (testDialog.textBox1.Text.Contains("<"))
                    returnText = true;
                if (testDialog.textBox1.Text.Contains(">"))
                    returnText = true;
                if (testDialog.textBox1.Text.Contains("\\"))
                    returnText = true;
                if (testDialog.textBox1.Text.Contains(":"))
                    returnText = true;
                if (testDialog.textBox1.Text.Contains("*"))
                    returnText = true;
                if (testDialog.textBox1.Text.Contains("\""))
                    returnText = true;
                if (testDialog.textBox1.Text.Contains("|"))
                    returnText = true;

                if (returnText == true)
                    MessageBox.Show(constant.idioma(numLanguage, 129), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                { }
                string result = list.CreateFolder(WithNotFirstPath(treeView1.SelectedNode.FullPath) + (treeView1.SelectedNode.FullPath.EndsWith("\\") ? "" : "\\") + testDialog.textBox1.Text, Constant.key());
                if (result.Equals("no"))
                    MessageBox.Show(constant.idioma(numLanguage, 130), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else if (result.Length > 0)
                    MessageBox.Show(constant.idioma(numLanguage, 131) + result);
                else
                {
                    MessageBox.Show(constant.idioma(numLanguage, 132), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    treeView1.SelectedNode.Nodes.Add(WithNotFirstPath(treeView1.SelectedNode.FullPath) + "\\", testDialog.textBox1.Text, 1, 2);
                }
            }
            else
            {

            }
            testDialog.Dispose();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (DialogResult.No == MessageBox.Show(constant.idioma(numLanguage, 161), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            { return; }

            if (!FirstNamePath(treeView1.SelectedNode.FullPath).Equals(Constant.Azure))
            {
                MessageBox.Show(constant.idioma(numLanguage, 127), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;

            }
            if (treeView1.SelectedNode.FullPath.Equals(Constant.Azure))
            {
                MessageBox.Show(constant.idioma(numLanguage, 133), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            string result = list.DeleteFolder(WithNotFirstPath(treeView1.SelectedNode.FullPath) + (treeView1.SelectedNode.FullPath.EndsWith("\\") ? "" : "\\"), Constant.key());
            if (result.Equals("no"))
                MessageBox.Show(constant.idioma(numLanguage, 134), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else if (result.Length > 0)
                MessageBox.Show(constant.idioma(numLanguage, 131) + result, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
            {
                MessageBox.Show(constant.idioma(numLanguage, 135), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                treeView1.SelectedNode.Remove();
            }

        }


        private void japonesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            numLanguage = 3;
            language(numLanguage);
        }

        private void 日本語ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            numLanguage = 1;
            language(numLanguage);
        }

        private void españolToolStripMenuItem_Click(object sender, EventArgs e)
        {
            numLanguage = 2;
            language(numLanguage);
        }


        private void language(int numLanguage)
        {

            this.Text = constant.idioma(numLanguage, 150);
            this.butCreateFolder.Text = constant.idioma(numLanguage, 151);
            this.butDeleteFile.Text = constant.idioma(numLanguage, 152);
            this.butDeleteFolder.Text = constant.idioma(numLanguage, 153);
            this.ingishToolStripMenuItem.Text = constant.idioma(numLanguage, 154);
            this.settingsToolStripMenuItem.Text = constant.idioma(numLanguage, 155);
            this.viewToolStripMenuItem.Text = constant.idioma(numLanguage, 157);
            this.listToolStripMenuItem.Text = constant.idioma(numLanguage, 158);
            this.normalToolStripMenuItem.Text = constant.idioma(numLanguage, 159);
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Account account = new Account(numLanguage);
            //account.Show();
            account.ShowDialog();

            treeView1.Nodes.Clear();
            listView1.Items.Clear();
            initializeListFile();
            showSplashScreen(2);

        }

        private void listToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1.View = View.List;
        }

        private void normalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1.View = View.LargeIcon;
        }
    }
}
